package leetcode;

public class Test2 {
    public static void main(String[] args) {
        int[] nums = new int[]{0, 1, 2, 2, 3, 0, 4, 2}; // 输入数组
        int val = 2; // 要移除的值
        int k = removeElement2(nums, val);
        System.out.println(k);
    }

    public static int removeElement(int[] nums, int val) {
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[k] = nums[i];
                k++;
            }
        }
        return k;
    }

    public static int removeElement2(int[] nums, int val) {
        int k = 0, l = nums.length - 1;
        while (k < l) {
            if (nums[k] == val) {
                nums[k] = nums[l--];
            } else {
                k++;
            }
        }
        return k;
    }
}
